<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <input type="text" v-model="form.userName">
    <input type="password" v-model="form.password">
    <img :src="imgBase64" @click="getQrCode">
    <button @click="login">登陆</button>
    <hr>
    <button @click="getUserInfo">获取当前登陆用户的信息</button>
    <hr>
    <button @click="downloadFile"> 下载视频</button>
    <button @click="aesTest">简单测试AES对称加密、解密简单测试</button>
    <hr>
    <button @click="downloadEncryptedContent">下载aes加密过的内容</button>
  </div>
</template>

<script>
import axios from 'axios'
import qs from 'qs'
import AesUtil from './lib/AesUtils'
import CryptoJS from "crypto-js";
import { encode, decode } from 'js-base64';

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      form: {
        userName: 'luo',
        password: '1234'
      },
      serverAddr: "http://192.168.1.140:9090",
      imgBase64: '',
      /**
       * 间隔询问是否已登陆的 timerId
       * */
      confirmLoginTimerId: null,
    }
  },
  mounted() {
    this.getQrCode()
    this.intervalGetUserInfo()
  },
  beforeDestroy() {
    clearInterval(this.confirmLoginTimerId)
  },
  methods: {

    getQrCode() {
      axios.get(this.serverAddr + "/loginQrCode").then(resp => {
        this.imgBase64 = resp.data.img
        localStorage.setItem("auth_token", resp.data.unAuthenticatedJwtToken)
      })
    },


    login() {

      axios.post(this.serverAddr + "/login?" + qs.stringify(this.form)).then(resp => {
        if (resp.data.code !== 200) {
          alert("登陆失败")
        } else {
          localStorage.setItem("auth_token", resp.data.auth_token)
          alert("登陆成功")
        }

      })
    },
    /**
     * 每间隔一秒获取一次用户的信息
     */
    intervalGetUserInfo() {

      this.confirmLoginTimerId = setInterval(() => {
        axios({
          url: this.serverAddr + "/userInfo",
          headers: {
            'auth_token': localStorage.getItem("auth_token")
          }
        }).then(resp => {
          if (resp.data.code === 200) {
            alert("登陆成功！" + resp.data.data.name)
            clearInterval(this.confirmLoginTimerId)
          }
        })
      }, 1000)


    },

    getUserInfo() {

      axios({
        url: this.serverAddr + "/userInfo",
        headers: {
          'Content-Type': 'application/json',
          'auth_token': localStorage.getItem("auth_token")
        }
      }).then(resp => {
        if (resp.data.code === 200) {

          alert("成功：" + resp.data.data.name)
        } else {
          alert("失败")
        }

      })

    },

    downloadFile() {
      axios.get(this.serverAddr + "/download", /*{参数Params},*/ {
        responseType: 'blob' // 如果没有加这句，可以使用 let blob = new Blob([res.data] 将响应转为 Blob 对象
      }).then(function (res) {
        var blob = res.data;

        this.downloadBlobObj(blob)
      });
    },

    downloadBlobObj(blob) {
      // FileReader主要用于将文件内容读入内存
      var reader = new FileReader();
      reader.readAsDataURL(blob);
      // onload当读取操作成功完成时调用
      reader.onload = function (e) {


        var a = document.createElement('a');
        // 获取文件名fileName
        // debugger
        var fileName = "download.txt"//res.headers["content-disposition"].split("=");
        // fileName = fileName[fileName.length - 1];
        // fileName = fileName.replace(/"/g, "");
        a.download = fileName;
        a.href = e.target.result;

        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
    },

    /**
     * AES对称加密、解密简单测试
     */
    aesTest() {
//字符串
      let text = "huanzi.qch@qq.com:欢子";

//key
      let genKey = AesUtil.genKey();
//key加密
      let ciphertext = AesUtil.encrypt(text, genKey);
      //key解密
      let plaintext = AesUtil.decrypt(ciphertext, genKey);

      console.log("key：");
      console.log(genKey);
      console.log("加密前：");
      console.log(text);
      console.log("key加密后：" + ciphertext);
      console.log("key解密后：");
      console.log(plaintext);
    },

    downloadEncryptedContent() {

      axios.get(this.serverAddr + "/downloadEncryptedContent").then(resp => {

        let plaintext = AesUtil.decrypt(resp.data.data, "MIGfMA0GCSqGSIb3");

        alert(plaintext)

        // const encryptedContent = decode(resp.data.data)
        // const decrypt = 'data:application/octet-stream;base64,'+AesUtil.decrypt(encryptedContent, "MIGfMA0GCSqGSIb3");
        // debugger
        // console.log("解密之后的内容是：", encryptedContent)
        // const blob = new Blob([encryptedContent]);

       /* let decrypt = 'data:application/octet-stream;base64,' + CryptoJS.AES.decrypt(resp.data.data, CryptoJS.enc.Utf8.parse("MIGfMA0GCSqGSIb3"), {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
        });*/

        // decrypt = decode(decrypt)

        // this.downloadBlobObj(decrypt)
        /*var a = document.createElement('a');
        // 获取文件名fileName
        // debugger
        var fileName = "example.txt"//res.headers["content-disposition"].split("=");
        // fileName = fileName[fileName.length - 1];
        // fileName = fileName.replace(/"/g, "");
        a.download = fileName;
        a.href = decrypt;

        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);*/


      })


    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>
